package com.shenhan.demo1;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author shenhan
 * @create 2020/6/9 10:13
 * @description
 */
public class Test2 {
    public static void main(String[] args) {
        Ticket2 ticket = new Ticket2();
        new Thread(() -> {for (int i = 0; i < 60; i++) {ticket.sale();}}, "A").start();
        new Thread(() -> {for (int i = 0; i < 60; i++) {ticket.sale();}}, "B").start();
        new Thread(() -> {for (int i = 0; i < 60; i++) {ticket.sale();}}, "C").start();
    }


}

class Ticket2 {
    private int number = 50;

    Lock lock = new ReentrantLock();

    public void sale() {
        lock.lock();
//        lock.tryLock();
        try {
            if (number > 0) {
                System.out.println(Thread.currentThread().getName() + "卖出了第" + (number--) + "张票，剩余" + number);
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        } finally {
            lock.unlock();
        }
    }
}
